package com.evoupsight.monitorpass.gateway.handlers;

import com.evoupsight.monitorpass.gateway.handlers.codec.MessageDecoder;
import com.evoupsight.monitorpass.gateway.handlers.codec.MessageEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.ByteOrder;
import java.util.concurrent.TimeUnit;

/**
 * 基于字节的自定义协议
 *
 * @author evoup
 */
@Component
@Qualifier("binaryProtocolInitializer")
public class BinaryProtocolInitializer extends ChannelInitializer<SocketChannel> {
    /**
     * 读操作空闲20秒
     */
    private final static int READER_IDLE_TIME_SECONDS = 20;
    /**
     * 写操作空闲20秒
     */
    private final static int WRITER_IDLE_TIME_SECONDS = 20;
    /**
     * 读写全部空闲40秒
     */
    private final static int ALL_IDLE_TIME_SECONDS = 40;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 添加用于解决粘包和拆包问题的处理器
        pipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 1024, 5, 8, 0, 0, false));
        pipeline.addLast(new LengthFieldPrepender(8));
        // 添加用于进行心跳检测的处理器
        pipeline.addLast("idleStateHandler", new IdleStateHandler(READER_IDLE_TIME_SECONDS, WRITER_IDLE_TIME_SECONDS, ALL_IDLE_TIME_SECONDS, TimeUnit.SECONDS));
        // 添加用于根据自定义协议将消息与字节流进行相互转换的处理器
        pipeline.addLast("decoder", new MessageDecoder());
        pipeline.addLast("encoder", new MessageEncoder());
        pipeline.addLast("handler", new ServerMessageHandler());
        // 添加客户端消息处理器(不需要添加，只实现服务端，最多用下单元测试)
        //pipeline.addLast(new ClientMessageHandler());

    }
}
